package cn.topcodes.tcsf.admin.jms;

import cn.topcode.unicorn.utils.StringUtil;
import cn.topcode.unicorn.utils.dist.DestType;
import cn.topcode.unicorn.utils.dist.DistEvent;
import cn.topcode.unicorn.utils.dist.DistEventConfig;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;

import javax.jms.Destination;
import java.util.HashMap;
import java.util.Map;

/**
 * 监听分布式事件，发布到消息队列中
 * Created by Unicorn on 2018/5/2.
 */
public class DistEventListener implements ApplicationListener<DistEvent> {

    @Autowired
    private JmsService jmsService;

    @Autowired(required = false)
    private DistEventRegister distEventRegister;

    private Map<String, Destination> map = new HashMap<>();

    @Override
    public void onApplicationEvent(DistEvent event) {
        if(distEventRegister == null) {
            return;
        }
        DistEventConfig distEventConfig = event.getClass().getAnnotation(DistEventConfig.class);
        if(distEventConfig == null ||
                distEventConfig.destType() == null) {
            return;
        }
        String type = distEventConfig.type();
        String destName = distEventConfig.destName();
        if(StringUtil.isBlank(type)) {
            type = event.getClass().getName();
        }
        if(StringUtil.isBlank(destName)) {
            destName = event.getClass().getName();
        }
        if(DestType.VIRTUAL_TOPIC.equals(distEventConfig.destType())) {
            destName = "VirtualTopic." + destName;
        }

        if(!distEventRegister.exist(type)) {
            return;
        }

        Destination dest = map.get(distEventConfig.destType() + "-" + destName);
        if(dest == null) {
            if(DestType.QUEUE.equals(distEventConfig.destType())) {
                dest = new ActiveMQQueue(destName);
            }else {
                dest = new ActiveMQTopic(destName);
            }
            map.put(distEventConfig.destType() + "-" + destName, dest);
        }
        jmsService.sendJson(dest, event);
    }
}
